#include "userservice.h"
#include "userrepository.h"

UserService::UserService(UserRepository *repository)
    : m_userRepository(repository)
{
}

void UserService::setUiPath(const QString &uiPath)
{
    m_uiPath = uiPath;
    if (m_userRepository) {
        // 重新构造一个 repository 也行，这里简化为更新路径
        m_userRepository -> setUiPath(m_uiPath);
    }
}

bool UserService::isValidNewUser(const QString &username, QString &errorMsg) const
{
    if (username.isEmpty()) {
        errorMsg = "Enter a username!";
        return false;
    }

    QStringList users = m_userRepository->loadUsers();
    if (users.contains(username)) {
        errorMsg = "User already exists!";
        return false;
    }
    return true;
}

bool UserService::isExistingUser(const QString &username, QString &errorMsg) const
{
    if (username.isEmpty()) {
        errorMsg = "Enter a username to delete!";
        return false;
    }

    QStringList users = m_userRepository->loadUsers();
    if (!users.contains(username)) {
        errorMsg = "User not found!";
        return false;
    }
    return true;
}

void UserService::addUser(const QString &username,
                          const QStringList &currentHiddenCtrls,
                          int existingUserCount)
{
    QStringList hiddenCtrls;
    if (existingUserCount == 0) {
        hiddenCtrls = currentHiddenCtrls;  // 第一个用户继承
    } else {
        hiddenCtrls.clear();               // 后续用户清空
    }

    if (m_userRepository) {
        m_userRepository->addUser(username, hiddenCtrls);
    }
}

void UserService::deleteUser(const QString &username)
{
    if (m_userRepository) {
        m_userRepository->deleteUser(username);
    }
}
